<template>
  <scroll-dialog
    v-if="type === 1"
    title="追加分类"
    ref="dialogRef"
    v-model:dialogVisible="diaLogVisible"
    @clickSubmit="clickSubmit"
    @close="close"
  >
    <el-cascader-panel
      v-model="selValue"
      :options="options"
      :props="cascaderProps"
      @change="change"
    />
  </scroll-dialog>
  <el-cascader
    v-else
    style="width: 100%"
    v-model="selValue"
    :options="options"
    :props="cascaderPropsLoad"
    @change="change"
  />
</template>
<script lang="ts" setup>
  import ScrollDialog from '@/components/ScrollDialog/index.vue'
  import { getGoodsTypes, getSaleTypes, addTypes } from '@/api/modules/shop'
  import type { getTypesItem } from '@/api/modules/shop'
  import { usePromise } from '@/hooks/core/usePromise.js'
  import { ref, onMounted, watch } from 'vue'
  import { useStops } from '@/views/shops/hooks/useShops'
  import common from '@/utils/common'
  import type { shop } from '@/types/shop'
  import type { PropType } from 'vue'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import { useStore } from 'vuex'
  import { computed } from '@vue/reactivity'
  import { cloneDeep } from 'lodash'
  const props = defineProps({
    diaLogVisible: {
      type: Boolean,
      default: false,
    },
    dataType: {
      type: Number,
      // 1 商品分类
      default: 1,
    },
    // 用户选择了的商品
    selItems: {
      type: Array as PropType<shop[]>,
      default() {
        return []
      },
    },
    type: {
      type: Number,
      default: 1,
    },
  })

  const selValue = ref([])
  const { to } = usePromise()
  const emits = defineEmits(['update:diaLogVisible', 'addSuccess'])
  const cascaderProps = {
    label: 'name',
    value: 'id',
    multiple: props.type === 1 ? true : false,
  }
  const cascaderPropsLoad = {
    lazy: true,
    label: 'name',
    value: 'id',
    multiple: props.type === 1 ? true : false,
    lazyLoad: (node: any, resolve: Function) => {
      // node.data.name node.data.id
      loadData({} as getTypesItem, resolve, node.data.name)
    },
  }
  const options = ref([])
  function initOptions() {
    const types = cloneDeep(store.getters.shopTypes)
    options.value = types.map((item: any) => {
      selValue.value.forEach((element) => {
        // @ts-ignore：无法被执行的代码的错误
        const [type, id] = element
        const tmpType = item.name === '商品分类' ? 1 : 2

        if (item.children) {
          item.children.map((e: any) => {
            if (type === tmpType && id === e.id) {
              e.disabled = true
            }
            return e
          })
        }
      })
      return item
    })
  }
  watch(
    () => options.value,
    (val) => {
      console.log('options.value =' + JSON.stringify(options.value))
    }
  )
  async function loadData(data: getTypesItem, resolve?: any, name?: string) {
    const [err, res] = await dicWithFunc(name, data)
    if (!err && resolve) {
      resolve(
        res.data.map((item: any) => {
          if (!item.isParent) item.leaf = true
          selValue.value.forEach((element) => {
            // @ts-ignore：无法被执行的代码的错误
            const [type, id] = element
            const tmpType = name === '商品分类' ? 1 : 2
            if (type === tmpType && id === item.id) item.disabled = true
          })
          return item
        })
      )
    } else if (err) {
      resolve([
        { name: '商品分类', id: 1 },
        { name: '营销分类', id: 2 },
      ])
    }
  }

  function dicWithFunc(type?: string, data?: any) {
    switch (type) {
      case '商品分类':
        return to(getGoodsTypes(data))
      case '营销分类':
        return to(getSaleTypes(data))
      default:
        return to(
          Promise.resolve({
            data: [
              { name: '商品分类', id: 1, isParent: true },
              { name: '营销分类', id: 2, isParent: true },
            ],
          })
        )
    }
  }

  const selNode: any = ref(null)
  function change(node: any) {
    console.log('node =' + JSON.stringify(node))
    selNode.value = node
  }
  const store = useStore()
  onMountedOrActivated(() => {
    if (!store.getters.shopTypes || store.getters.shopTypes.length <= 0) {
      store.dispatch('shop/loadTypes')
    }
  })
  function initForm(selItems: any = []) {
    selValue.value = []
    if (selItems.length === 1) {
      const { goodsTypeIds = [], saleTypeIds = [] } = selItems[0]
      goodsTypeIds.forEach((id: number) => {
        // @ts-ignore：无法被执行的代码的错误
        selValue.value.push([1, id])
      })
      saleTypeIds.forEach((id: number) => {
        // @ts-ignore：无法被执行的代码的错误
        selValue.value.push([2, id])
      })
    }
    initOptions()
  }
  defineExpose({ initForm })
  const dialogRef = ref()
  const { addTypesToSections } = useStops()
  async function clickSubmit() {
    if (
      props.selItems?.length === 0 ||
      !selNode.value ||
      selNode?.value.length === 0
    ) {
      common.XmMessage(1, '商品和分类，都至少选择一项')
      return
    }
    const { index1, index2 } = addTypesToSections(selNode.value)
    const spuIds = props.selItems.map((item: shop) => {
      return item.id
    })
    common.XmLoading()
    const [err, res] = await to(
      addTypes({ goodsTypeIds: index1, saleTypeIds: index2, spuIds })
    )
    common.XmLoading(false)
    if (!err) {
      close()
      emits('addSuccess', res.data)
    }
  }
  function close() {
    selNode.value = null
    options.value = []
    emits('update:diaLogVisible', false)
  }
</script>
<style lang="scss" scoped>
  .el-form-item__content {
    :deep(.el-cascader) {
      width: 100%;
    }
  }
</style>
